package org.dromara.merchants.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.merchants.domain.TaAssociation;
import org.dromara.merchants.domain.vo.TaGroupGoodsVo;
import org.dromara.merchants.mapper.TaAssociationMapper;
import org.springframework.stereotype.Service;
import org.dromara.merchants.domain.bo.TaGoodsBo;
import org.dromara.merchants.domain.vo.TaGoodsVo;
import org.dromara.merchants.domain.TaGoods;
import org.dromara.merchants.mapper.TaGoodsMapper;
import org.dromara.merchants.service.ITaGoodsService;

import com.baomidou.mybatisplus.core.conditions.Wrapper;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;

/**
 * 商品Service业务层处理
 *
 * @author xiyin321
 * @date 2024-07-02
 */
@RequiredArgsConstructor
@Service
public class TaGoodsServiceImpl implements ITaGoodsService {

    private final TaGoodsMapper baseMapper;
    private final TaAssociationMapper associationMapper;

    /**
     * 查询商品
     */
    @Override
    public TaGoodsVo queryById(Long id) {
        TaGoodsVo vo = baseMapper.selectVoById(id);
        vo.setAssociationList(associationMapper.selectAssociationListById(vo.getGoodsId(), "0"));
        return vo;
    }

    /**
     * 查询商品列表
     */
    @Override
    public TableDataInfo<TaGoodsVo> queryPageList(TaGoodsBo bo, PageQuery pageQuery) {
        Page<TaGoodsVo> result = baseMapper.selectGoodsPage(pageQuery.build(), this.buildQueryWrapper(bo));
        result.getRecords().forEach(item -> {
            item.setAssociationList(associationMapper.selectAssociationListById(item.getGoodsId(), "0"));
        });
        return TableDataInfo.build(result);
    }

    /**
     * app端查询商品列表
     *
     * @param bo
     * @param pageQuery
     */
    @Override
    public TableDataInfo<TaGoodsVo> queryAppList(TaGoodsBo bo, PageQuery pageQuery) {
        bo.setIsStatus("0");
        Page<TaGoodsVo> result = baseMapper.selectAppPage(pageQuery.build(), this.buildQueryWrapper(bo));
        result.getRecords().forEach(item -> {
            item.setAssociationList(associationMapper.selectAssociationListById(item.getGoodsId(), "0"));
        });
        return TableDataInfo.build(result);
    }

    /**
     * app端查询商品列表 提供店铺进行分类
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<TaGroupGoodsVo> queryAppGroupList(TaGoodsBo bo, PageQuery pageQuery) {
        bo.setIsStatus("0");
        Page<TaGroupGoodsVo> result = baseMapper.selectGroupPage(pageQuery.build(), this.buildQueryWrapper(bo));
        result.getRecords().forEach(item -> {
            item.setGoodsTotal(item.getGoodsList().size());
        });
        result.setTotal(result.getRecords().size());
        return TableDataInfo.build(result);
    }

    /**
     * 查询商品下拉列表
     *
     * @param bo
     * @return
     */
    @Override
    public List<TaGoodsVo> queryOptionList(TaGoodsBo bo) {
        bo.setIsStatus("0");
        return baseMapper.selectGoodsList(this.buildQueryWrapper(bo));
    }

    /**
     * 查询商品列表
     */
    @Override
    public List<TaGoodsVo> queryList(TaGoodsBo bo) {
        return baseMapper.selectVoList(this.buildQueryWrapper(bo));
    }

    /*构建查询条件*/
    private Wrapper<TaGoods> buildQueryWrapper(TaGoodsBo bo) {
        QueryWrapper<TaGoods> wrapper = Wrappers.query();
        wrapper.eq("g.del_flag", "0")
            .eq(StringUtils.isNotBlank(bo.getGoodsName()), "g.goods_name", bo.getGoodsName())
            .eq(ObjectUtil.isNotNull(bo.getStoreId()), "g.store_id", bo.getStoreId())
            .eq(ObjectUtil.isNotNull(bo.getClassificationId()), "g.classification_id", bo.getClassificationId())
            .eq(ObjectUtil.isNotNull(bo.getCategoryId()), "g.category_id", bo.getCategoryId())
            .eq(ObjectUtil.isNotNull(bo.getIsStatus()), "g.is_status", bo.getIsStatus());
        return wrapper;
    }

    private LambdaQueryWrapper<TaGoods> buildLambdaQueryWrapper(TaGoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TaGoods> lqw = Wrappers.lambdaQuery();
        lqw.
            like(StringUtils.isNotBlank(bo.getGoodsName()), TaGoods::getGoodsName, bo.getGoodsName())
            .eq(ObjectUtil.isNotNull(bo.getStoreId()), TaGoods::getStoreId, bo.getStoreId())
            .eq(ObjectUtil.isNotNull(bo.getClassificationId()), TaGoods::getClassificationId, bo.getClassificationId())
            .eq(ObjectUtil.isNotNull(bo.getCategoryId()), TaGoods::getCategoryId, bo.getCategoryId())
            .eq(TaGoods::getIsStatus, '0');
        return lqw;
    }


    /**
     * 新增商品
     */
    @Override
    public Boolean insertByBo(TaGoodsBo bo) {
        List<TaAssociation> associations = MapstructUtils.convert(bo.getAssociationList(), TaAssociation.class);
        TaGoods add = MapstructUtils.convert(bo, TaGoods.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (associations != null) {
            associations.forEach(item -> {
                item.setParentId(add.getGoodsId());
            });
        }
        /*将商品规格插入*/
        associationMapper.insertBatch(associations);
        if (flag) {
            bo.setGoodsId(add.getGoodsId());
        }
        return flag;
    }

    /**
     * 修改商品
     */
    @Override
    public Boolean updateByBo(TaGoodsBo bo) {
        List<TaAssociation> associations = MapstructUtils.convert(bo.getAssociationList(), TaAssociation.class);
        TaGoods update = MapstructUtils.convert(bo, TaGoods.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (associations != null) {
            associations.forEach(item -> {
                item.setParentId(update.getGoodsId());
            });
        }
        associationMapper.delete(new LambdaQueryWrapper<TaAssociation>().eq(TaAssociation::getParentId,update.getGoodsId()));
        /*插入新的商品规格*/
        associationMapper.insertBatch(associations);
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TaGoods entity) {
        //TODO 做一些数据校验,如唯一约束
        /*对商品名称进行校验*/
        if (StringUtils.isNotBlank(entity.getGoodsName())) {
            TaGoods goods = baseMapper.selectOne(new LambdaQueryWrapper<TaGoods>().eq(TaGoods::getGoodsName, entity.getGoodsName()));
            if (goods != null && !Objects.equals(goods.getGoodsId(), entity.getGoodsId())) {
                throw new ServiceException("商品名称重复");
            }
        }
    }

    /**
     * 批量删除商品
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            /*在删除商品时，将关联表的相关记录删除*/
            associationMapper.delete(new LambdaQueryWrapper<TaAssociation>().in(TaAssociation::getParentId, ids));
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
